<template>
  <div class="xtx-wrapper">
    <div class="container">
      <!-- 卡片 -->
      <div class="xtx-card">
        <h3>新用户注册</h3>
        <ValidationObserver v-slot="{ invalid }" tag="form" class="xtx-form">
          <ValidationProvider
            tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|username"
            name="用户名称"
          >
            <span class="iconfont icon-zhanghao"></span>
            <input
              :class="{error:errors[0]}"
              v-model.trim="username"
              type="text"
              placeholder="设置用户名称"
            />
            <i v-show="errors[0]" class="iconfont icon-warning err">{{errors[0]}}</i>
          </ValidationProvider>
          <ValidationProvider
            tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|mobile"
            name="手机号码"
            ref="mobile"
          >
            <span class="iconfont icon-phone"></span>
            <input
              v-model.trim="mobile"
              :class="{error:errors[0]}"
              type="text"
              placeholder="输入手机号码  "
            />
            <i v-show="errors[0]" class="iconfont icon-warning err">{{errors[0]}}</i>
          </ValidationProvider>
          <ValidationProvider
            tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|code"
            name="验证码"
          >
            <span class="iconfont icon-xiaoxi"></span>
            <input v-model.trim="code" :class="{error:errors[0]}" type="text" placeholder="短信验证码" />
            <a @click="send()" class="code" :class="{ing:timer}" href="javascript:;">{{sendText}}</a>
            <i v-show="errors[0]" class="iconfont icon-warning err">{{errors[0]}}</i>
          </ValidationProvider>
          <ValidationProvider
            tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|password:@confirm"
            name="密码"
          >
            <span class="iconfont icon-suo"></span>
            <input
              v-model.trim="password"
              :class="{error:errors[0]}"
              type="password"
              placeholder="设置6至20位字母、数字和符号组合"
            />
            <i v-show="errors[0]" class="iconfont icon-warning err">{{errors[0]}}</i>
          </ValidationProvider>
          <ValidationProvider
            tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required"
            vid="confirm"
            name="确认密码"
          >
            <span class="iconfont icon-suo"></span>
            <input
              v-model.trim="confirm"
              :class="{error:errors[0]}"
              type="password"
              placeholder="请再次输入上面密码"
            />
            <i v-show="errors[0]" class="iconfont icon-warning err">{{errors[0]}}</i>
          </ValidationProvider>
          <ValidationProvider tag="div" class="xtx-form-item" v-slot="{errors}" rules="isAgree">
            <div class="agree">
              <xtx-checkbox v-model="isAgree"></xtx-checkbox>已阅读并同意
              <i>《用户服务协议》</i>
            </div>
            <i v-show="errors[0]" class="iconfont icon-warning err">{{errors[0]}}</i>
          </ValidationProvider>
          <div class="xtx-form-item">
            <button @click.prevent="register" class="submit" :disabled="invalid">立即注册</button>
          </div>
        </ValidationObserver>
      </div>
    </div>
  </div>
</template>

<script>
import { extend, ValidationProvider, ValidationObserver, configure } from 'vee-validate'
import { required } from 'vee-validate/dist/rules'
import http from '@/utils/request.js'
configure({ enent: 'blur' })
// 必填
extend('required', {
  ...required,
  message: '请输入{_field_}'
})
// 用户名
extend('username', {
  validate: async (value) => {
    // 校验格式
    if (value.length > 20) {
      return '用户名称是20个字以内'
    }
    // 校验是否存在
    const { data } = await http.get(`register/check?account=${value}`)
    if (data.result.valid) {
      return '用户名已存在，请换一个'
    }
    return true
  }
})
// 手机号
extend('mobile', {
  validate: (value) => {
    // 校验格式
    if (!/^1[3-9]\d{9}$/.test(value)) {
      return '手机号格式不正确'
    }
    return true
  }
})
// 手机号
extend('code', {
  validate: (value) => {
    // 校验格式
    if (!/^\d{6}$/.test(value)) {
      return '验证码6个数字'
    }
    return true
  }
})
// 密码
extend('password', {
  params: ['target'],
  validate: (value, { target }) => {
    // 校验格式
    if (!/^\w{6,20}$/.test(value)) {
      return '密码是6-20个字符'
    }
    if (value !== target) {
      return '两次输入的密码不一致'
    }
    return true
  }
})

extend('isAgree', {
  validate: (value) => {
    // 校验格式
    if (value !== true) {
      return '请同意用户协议条款'
    }
    return true
  }
})

export default {
  components: {
    ValidationProvider,
    ValidationObserver
  },
  name: 'register-page',
  data () {
    return {
      isAgree: true,
      username: '',
      mobile: '',
      code: '',
      password: '',
      confirm: '',
      // 定时器
      timer: null,
      sendText: '发送验证码'
    }
  },
  methods: {
    register () {
      const { username: account, mobile, code, password } = this
      this.$http
        .post('register', { account, mobile, code, password })
        .then(() => {
          this.$router.push('/login')
        })
    },
    async send () {
      // 校验下手机号
      const { valid } = await this.$refs.mobile.validate()
      await this.$http.get('/register/code', { params: { mobile: this.mobile } })
      if (valid && !this.timer) {
        let time = 60
        this.sendText = '60s后重发'
        this.timer = setInterval(() => {
          time = time - 1
          if (time <= 0) {
            window.clearInterval(this.timer)
            this.timer = null
            this.sendText = '发送验证码'
          } else {
            this.sendText = `${time}s后重发`
          }
        }, 1000)
      }
    }
  }
}
</script>

<style scoped lang='less'>
@import "./styles/register.less";
</style>
